package leetcode.code1253;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：7 ms, 在所有 Java 提交中击败了81.58%的用户
//
//内存消耗：50.1 MB, 在所有 Java 提交中击败了69.74%的用户
//
//通过测试用例：69 / 69

public class Solution implements IDebug {

	public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {
		List<List<Integer>> ans = new ArrayList<>();
		int sum = 0;
		int two = 0;
		for (int num : colsum) {
			two += num == 2 ? 1 : 0;
			sum += num;
		}
		// 满足如下条件，无法分
		if (sum != upper + lower || two > upper || two > lower) {
			return ans;
		}
		int len = colsum.length;
		int one = upper - two;// upper可以承担的1的数量
		List<Integer> listUpper = new ArrayList<>();
		List<Integer> listLower = new ArrayList<>();
		for (int i = 0; i < len; i++) {
			int num = colsum[i];
			if (num == 2) {
				listUpper.add(1);
				listLower.add(1);
			} else if (num == 1) {
				if (one > 0) {
					listUpper.add(1);
					listLower.add(0);
					one -= 1;// 承担数量减少1
				} else {
					listUpper.add(0);
					listLower.add(1);
				}
			} else {
				listUpper.add(0);
				listLower.add(0);
			}
		}
		ans.add(listUpper);
		ans.add(listLower);
		return ans;
	}

	@Override
	public void debug1() {
		List<List<Integer>> e = HelpDebug.str2intlist1("[[1,1,0],[0,0,1]]");
		HelpDebug.compare(e, this.reconstructMatrix(2, 1, HelpDebug.str2array3("[1,1,1]")));
	}

	@Override
	public void debug2() {
		List<List<Integer>> e = HelpDebug.str2intlist1("[[1,1,0],[0,0,1]]");
		HelpDebug.compare(e, this.reconstructMatrix(2, 1, HelpDebug.str2array3("[1,1,1]")));
	}

	@Override
	public void debug3() {
		List<List<Integer>> e = HelpDebug.str2intlist1("[]");
		HelpDebug.compare(e, this.reconstructMatrix(2, 3, HelpDebug.str2array3("[2,2,1,1]")));
	}

	@Override
	public void debug4() {
		List<List<Integer>> e = HelpDebug.str2intlist1("[[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]");
		HelpDebug.compare(e, this.reconstructMatrix(5, 5, HelpDebug.str2array3("[2,1,2,0,1,0,1,2,0,1]")));
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
